<template>
  <div class="quality_problem">
    <one-title title="车间质量问题分析" @refreshData="refresh"></one-title>
    <div class="fixed_top_56">
      <div class="multiple_search">
        <div class="search_item">
          <div class="select_label">
            <el-select v-model="selectType"
                       @change="_selectType"
                       size="small">
              <el-option value="workGroup" label="班组"></el-option>
              <el-option value="workStage" label="工序"></el-option>
            </el-select>
          </div>
          <div class="search_wrapper marLeft">
            <el-select v-model="workgroupId"
                       v-show="selectType === 'workGroup'"
                       placeholder="请选择班组"
                       size="small">
              <el-option
                v-for="(item, index) in workGroup"
                :key="index"
                :label="item.LABEL"
                :value="item.ID">
              </el-option>
            </el-select>
            <el-select v-model="workstageIds"
                       v-show="selectType === 'workStage'"
                       multiple
                       collapse-tags
                       placeholder="请选择工序"
                       filterable
                       size="small">
              <el-option
                v-for="(item, index) in workStageList"
                :key="index"
                :label="item.LABEL"
                :value="item.ID">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="search_item">
          <span class="search_label">工序完成日期：</span>
          <el-date-picker
            v-model="completionDate"
            type="daterange"
            size="small"
            align="right"
            unlink-panels
            :clearable=false
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
        <div class="mes_btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            class="search_btn"
            @click="init">
          </el-button>
        </div>
      </div>
      <div class="chart_box">
        <div ref="myChart" class="chart_wrapper" v-loading="isLoading"></div>
      </div>
      <div class="table_container">
        <el-table
          :data="listData"
          ref="tableNode"
          max-height="440"
          v-loading="isLoading"
          border
          stripe
          @sort-change="_sort"
          tooltip-effect="dark">
          <el-table-column
            label="工序名称"
            width="200">
            <template slot-scope="scope">
              {{scope.row.workstageNumber + '/' + scope.row.workstageName}}
            </template>
          </el-table-column>
          <el-table-column
            label="问题类型">
            <mes-column :key="index" v-for="(column, index) in tableColumns" :column="column"></mes-column>
          </el-table-column>
          <el-table-column
            label="总数"
            prop="total"
            sortable="custom"
            align="center"
            :resizable="false"
            min-width="120">
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import tableColumns from './tableColumns'

export default {
  name: 'QualityProblem',
  components: {},
  data() {
    return {
      tableColumns: tableColumns, // table列配置
      isLoading: false, // 加载状态
      sortData: {}, // 排序对象
      selectType: 'workGroup', // 筛选类型
      workgroupId: '', // 班组
      workstageIds: [], // 工序
      completionDate: [
        this.moment(window.serverTime).subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
        this.moment(window.serverTime).format('YYYY-MM-DD 23:59:59')
      ], //工序完成日期
      workStage: [], // eCharts X轴
      materialDefect: [], // 材料缺陷
      deviceDefect: [], // 器件缺陷
      operationalErrors: [], // 操作失误
      designDefect: [], // 设计缺陷
      equipmentFailure: [], // 设备故障
      processDefect: [], // 工艺缺陷
      other: [], // 其他
      pickerOptions: this.$dateConfig.pickerOptions // 日期格式的快捷键配置项
    }
  },
  computed: {
    // 班组
    workGroup() {
      let workGroup = this.$store.state.qualityProblem.workGroup
      return workGroup.length > 0 ? [{ID: '', LABEL: '全部'}, ...workGroup] : workGroup
    },
    // 工序
    workStageList() {
      return this.$store.state.qualityProblem.workStageList
    },
    // 图表数据
    listData() {
      return this.$store.state.qualityProblem.listData || []
    },
  },
  mounted() {
    this.getWorkStage()
    this.getWorkGroup()
    this.init()
  },
  methods: {
    // 刷新
    refresh() {
      this.completionDate = [
        this.moment(window.serverTime).subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
        this.moment(window.serverTime).format('YYYY-MM-DD 23:59:59')
      ]
      this._selectType()
      this.init()
    },
    // 初始化
    init() {
      this.isLoading = true
      let postData = {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/workshopquanlityproblemreport',
        data: {},
        module: 'qualityProblem',
        state: 'listData'
      }
      if (this.workgroupId) {
        postData.data.workgroupId = this.workgroupId
      } else if (this.workstageIds.length) {
        postData.data.workstageIds = this.workstageIds.join(',')
      }
      if (this.completionDate.length > 0) {
        postData.data.beginWorkStageDate = this.completionDate[0]
        postData.data.endWorkStageDate = this.completionDate[1]
      }
      if (Object.keys(this.sortData).length > 0) {
        postData.data.sort = this.sortData
      }
      this.$store.dispatch('saveData', postData).then(res => {
        // 初始化图表数据
        this.eChartsComputed()
        // 设置图表滚动
        let dataZoom = [
          // {
          //   type: 'inside',
          //   show: false,
          //   showDetail: false,
          //   start: 0,
          //   end: 100
          // },
          {
            type: 'slider',
            show: false,
            showDetail: false,
            start: 0,
            end: 100,
            bottom: 10,
            height: 16,
            handleStyle: {
              /*手柄的样式*/
              color: '#fff',
              borderWidth: 2,
              borderColor: '#a1b1c1'
            }
          }
        ]
        let max = 12
        if (res.length >= max) {
          let end = Math.floor(max / res.length * 100)
          dataZoom.forEach(item => {
            item.end = end
            item.show = true
          })
        }
        this.drawLine(dataZoom)
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 获取班组列表
    getWorkGroup() {
      this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/workgroup/workgroup/listfields/id,name as label',
        module: 'qualityProblem',
        state: 'workGroup'
      }).then(res => {
      })
    },
    // 获取工序列表
    getWorkStage() {
      this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/workstagerepository/workstageRepository/listfields/id,name as label',
        module: 'qualityProblem',
        state: 'workStageList'
      }).then(res => {
      })
    },
    // 切换选项时，把值清空
    _selectType() {
      this.workgroupId = '' // 班组
      this.workstageIds = [] // 工序
    },
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    // 计算图表所需数据
    eChartsComputed() {
      // eCharts X轴
      this.workStage = []
      // 材料缺陷
      this.materialDefect = []
      // 器件缺陷
      this.deviceDefect = []
      // 操作失误
      this.operationalErrors = []
      // 设计缺陷
      this.designDefect = []
      // 设备故障
      this.equipmentFailure = []
      // 工艺缺陷
      this.processDefect = []
      // 其他
      this.other = [] //表格的数据
      this.listData.forEach(item => {
        this.workStage.push(item.workstageName + '/' + item.workstageNumber || '')
        this.materialDefect.push(item.materialDefect || 0)
        this.deviceDefect.push(item.equipmentDefect || 0)
        this.operationalErrors.push(item.misoperation || 0)
        this.designDefect.push(item.designDefect || 0)
        this.equipmentFailure.push(item.deviceTrouble || 0)
        this.processDefect.push(item.technologyDefect || 0)
        this.other.push(item.others || 0)
      })
    },
    // 绘制图表
    drawLine(dataZoom) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.myChart)
      // 图表配置
      myChart.setOption({
        // 弹框样式
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'},
          padding: 10,
          textStyle: {fontSize: 12},
          backgroundColor: 'rgba(0, 0, 0, 0.85)',
        },
        // 缩放，滚动
        dataZoom: dataZoom,
        // 画板边距
        grid: {
          left: '60',
          right: '60',
        },
        legend: {
          data: [
            {name: '原材料缺陷'},
            {name: '器件缺陷'},
            {name: '操作失误'},
            {name: '设计缺陷'},
            {name: '设备故障'},
            {name: '工艺缺陷'},
            {name: '其他'},
          ],
          itemWidth: 24,
          itemHeight: 10,
        },
        xAxis: {
          type: 'category',
          // boundaryGap: false,
          data: this.workStage,
          // x轴轴线颜色和宽度
          axisLine: {
            lineStyle: {
              color: '#dcdfe6',
              width: 2
            }
          },
          // x轴字体颜色
          axisLabel: {
            show: true,
            textStyle: {
              color: 'rgba(0, 0, 0, 0.65)'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '次数',
          // 设置Y轴刻度线最高值根据数据的最大值变化
          // max: (value) => {
          //   return Math.ceil(value.max * 1)
          // },
          // Y轴虚线
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 0, 0, 0.1)',
              width: 1,
              type: 'dashed'
            }
          },
          // y轴线
          axisLine: {'show': false},
          //y轴刻度线
          axisTick: {'show': false},
        },
        // 数据
        series: [
          {
            name: '原材料缺陷',
            type: 'bar',
            stack: '问题类型',
            data: this.materialDefect,
            barMaxWidth: 160,
            barMinHeight: 0,
            itemStyle: {
              normal: {
                color: '#1890ff',
                opacity: 0.85
              }
            }
          },
          {
            name: '器件缺陷',
            type: 'bar',
            stack: '问题类型',
            data: this.deviceDefect,
            barMaxWidth: 160,
            itemStyle: {
              normal: {
                color: '#37cccc',
                opacity: 0.85
              }
            }
          },
          {
            name: '操作失误',
            type: 'bar',
            stack: '问题类型',
            data: this.operationalErrors,
            barMaxWidth: 160,
            itemStyle: {
              normal: {
                color: '#4ecc74',
                opacity: 0.85
              }
            }
          },
          {
            name: '设计缺陷',
            type: 'bar',
            stack: '问题类型',
            data: this.designDefect,
            barMaxWidth: 160,
            itemStyle: {
              normal: {
                color: '#fbd438',
                opacity: 0.85
              }
            }
          },
          {
            name: '设备故障',
            type: 'bar',
            stack: '问题类型',
            data: this.equipmentFailure,
            barMaxWidth: 160,
            itemStyle: {
              normal: {
                color: '#f04864',
                opacity: 0.85
              }
            }
          },
          {
            name: '工艺缺陷',
            type: 'bar',
            stack: '问题类型',
            data: this.processDefect,
            barMaxWidth: 160,
            itemStyle: {
              normal: {
                color: '#9860e5',
                opacity: 0.85
              }
            }
          },
          {
            name: '其他',
            type: 'bar',
            stack: '问题类型',
            data: this.other,
            barMaxWidth: 160,
            itemStyle: {
              normal: {
                color: '#5354d0',
                opacity: 0.85
              }
            }
          }
        ]
      })
    },
  }
}
</script>

<style scoped lang="less">
  .quality_problem {
    .chart_box {
      padding: 0 20px;
      .chart_wrapper {
        width: 100%;
        height: 500px;
        box-sizing: border-box;
        border: 1px solid #dcdfe6;
        margin-bottom: 20px;
        padding-top: 20px;
      }
    }
    .table_container{
      padding-bottom: 40px;
    }
    .select_label {
      flex: 100px;
      width: 100px;
    }
    .marLeft {
      margin-left: -1px;
    }
  }
</style>
